package com.scanner.util;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;

import com.scanner.bean.ScanSetting;
import com.google.gson.Gson;

import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BaseUtils {

    private static long lastClickTime;
    public synchronized static boolean isFastClick() {
        long time = System.currentTimeMillis();
        if ( time - lastClickTime < 500) {
            return true;
        }
        lastClickTime = time;
        return false;
    }


    private static long lastClickTime2;
    public synchronized static boolean isFastClick2() {
        long time = System.currentTimeMillis();
        if ( time - lastClickTime2 < 500) {
            return true;
        }
        lastClickTime2 = time;
        return false;
    }

    /**
     * 获取app 版本信息
     */
    public static String getAppVersionName(Context context) {

        PackageManager packageManager = context.getPackageManager(); // getPackageName()是你当前类的包名，0代表是获取版本信息

        PackageInfo packInfo = null;
        try {
            packInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        String version = "";
        if(packInfo!=null){
            version = packInfo.versionName;
        }
        return version;
    }


    /**
     * [获取应用程序版本名称信息]
     * @param context
     * @return 当前应用的版本名称
     */
    public static synchronized int getVersionCode(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }


    /**
     * 版本号比较 * * @param version1 * @param version2 * @return
     * ：0代表相等，1代表version1大于version2，-1代表version1小于version2
     */
    public static int compareVersion(String version1, String version2) {
        if(judgeContainsStr(version1)){
            return 0;
        }
        if (version1.equals(version2)) {
            return 0;
        }
        String[] version1Array = version1.split("\\.");
        String[] version2Array = version2.split("\\.");
        LogUtil.d("version1Array==" + version1Array.length);
        LogUtil.d("version2Array==" + version2Array.length);
        int index = 0;
        // 获取最小长度值
        int minLen = Math.min(version1Array.length, version2Array.length);
        int diff = 0;
        //         循环判断每位的大小
        LogUtil.d("verTag2=2222=" + version1Array[index]);
        while (index < minLen && (diff = Integer.parseInt(version1Array[index]) - Integer.parseInt(version2Array[index])) == 0) {
            index++;
        }
        if (diff == 0) {//         如果位数不一致，比较多余位数
            for (int i = index; i < version1Array.length; i++) {
                if (Integer.parseInt(version1Array[i]) > 0) {
                    return 1;
                }
            }
            for (int i = index; i < version2Array.length; i++) {
                if (Integer.parseInt(version2Array[i]) > 0) {
                    return -1;
                }
            }
            return 0;
        } else {
            return diff > 0 ? 1 : -1;
        }
    }

    /**
     * 该方法主要使用正则表达式来判断字符串中是否包含字母
     * @author fenggaopan 2015年7月21日 上午9:49:40
     * @param cardNum 待检验的原始卡号
     * @return 返回是否包含
     */
    public static boolean judgeContainsStr(String cardNum) {
        String regex=".*[a-zA-Z]+.*";
        Matcher m= Pattern.compile(regex).matcher(cardNum);
        return m.matches();
    }


    public static String getLocalLanguage(Context context){
        Locale locale;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            locale = context.getResources().getConfiguration().getLocales().get(0);
        } else {
            locale = context.getResources().getConfiguration().locale;
        }
        //或者仅仅使用 locale = Locale.getDefault();
        //不需要考虑接口 deprecated(弃用)问题
        String lang = locale.getLanguage();
        return lang;
    }


    /**
     * 获取保存在本地的配置信息
     * @return
     */
    public static ScanSetting getSettingFormShare(){
        String scanSetting = SharePreConfig.getScanSetting();
        Gson gson = new Gson();
        ScanSetting setting = gson.fromJson(scanSetting, ScanSetting.class);
        return setting == null ? new ScanSetting() : setting;
    }

    /**
     * 更新本地配置信息
     * @param scanSetting
     */
    public static void beanToString(ScanSetting scanSetting){
        LogUtil.d("更新本地配置信息=="+scanSetting.toString());
        Gson gson = new Gson();
        SharePreConfig.setScanSetting(gson.toJson(scanSetting));
    }

    /**
     * 字符串转换成十六进制字符串
     * str 待转换的ASCII字符串
     * @return String 每个Byte之间空格分隔，如: [61 6C 6B]
     */
    public static String str2HexStr(String str)
    {

        char[] chars = "0123456789ABCDEF".toCharArray();
        StringBuilder sb = new StringBuilder("");
        byte[] bs = str.getBytes();
        int bit;

        for (int i = 0; i < bs.length; i++)
        {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = bs[i] & 0x0f;
            sb.append(chars[bit]);
            sb.append(' ');
        }
        return sb.toString().trim();
    }

    /**
     * bytes字符串转换为Byte值
     * @param  src Byte字符串，每个Byte之间没有分隔符
     * @return byte[]
     */
    public static byte[] hexStr2Bytes(String src)
    {
        int m=0,n=0;
        int l=src.length()/2;
        System.out.println(l);
        byte[] ret = new byte[l];
        for (int i = 0; i < l; i++)
        {
            m=i*2+1;
            n=m+1;
            ret[i] = Byte.decode("0x" + src.substring(i*2, m) + src.substring(m,n));
        }
        return ret;
    }


    //遍历数组
    public static int printArray(String[] array,String value){
        for(int i = 0;i<array.length;i++){
            if(array[i].equals(value)){
                return i;
            }
        }
        return 0;//当if条件不成立时，默认返回一个负数值-1
    }
}
